package com.dm.cloud.utils;

import com.dm.cloud.common.CommonDto;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class DtoPreOpratrionUtils<T> {

    public void preInsert(T t){
        if(t instanceof CommonDto) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String authorization = request.getHeader("Authorization");

            UserDetails user = Oauth2Utils.getByAuthorization(authorization);

            //用户信息
            CommonDto t1 = (CommonDto) t;
            t1.setCreateBy(user.getUsername());
            t1.setUpdateBy(user.getUsername());

            Date dt = new Date();
            t1.setCreateDate(dt);
            t1.setUpdateDate(dt);
        }
    }

    public void preUpdate(T t){
        if(t instanceof CommonDto) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String authorization = request.getHeader("Authorization");

            UserDetails user = Oauth2Utils.getByAuthorization(authorization);

            CommonDto t1 = (CommonDto) t;
            t1.setUpdateBy(user.getUsername());

            Date dt = new Date();
            t1.setUpdateDate(dt);
        }
    }
}
